package com.cdtu;

import com.cdtu.handler.DisplayMessageHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author Mika
 * @date 2025/02/28 13:34
 **/
@Slf4j
public class NettyServer {
    // 定时调度执行，线程池
        protected static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(20);
    // 记录 client id 与 channel 的映射关系
    public static ConcurrentHashMap<String, Channel> channels = new ConcurrentHashMap<>();
    // 存放所有的连接
    public static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 启动服务
    public static void startServer() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1), workerGroup = new NioEventLoopGroup(32);  //线程数先限制一下
        EventLoopGroup handlerGroup = new DefaultEventLoopGroup();  //使用DefaultEventLoop来处理其他任务
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                // 当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。
                .option(ChannelOption.SO_BACKLOG, 300)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) {
                        channel.pipeline()
                                .addLast(new IdleStateHandler(60, 30, 0))
                                .addLast(new DisplayMessageHandler());
//                                .addLast(new WriteOrderHandler());
                    }
                })
                // 不接受延迟，保证实时性，尽可能快速发送
                .childOption(ChannelOption.TCP_NODELAY, true)
                // 保持长连接
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        int port = 60000;
        ChannelFuture channelFuture = bootstrap.bind(port);
        try {
            channelFuture.sync();
            log.info("分站服务端在 {} 启动，状态为： {}", port, channelFuture.isDone());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
